package com.sgb.kjwl.view.ui.activity.self.shop;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Build;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;

import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.ActivityShopGoodsDetailBinding;
import com.sgb.kjwl.di.material.DaggerMaterialComponent;
import com.sgb.kjwl.di.material.MaterialModule;
import com.sgb.kjwl.model.entity.AddShoppingCar;
import com.sgb.kjwl.model.entity.ConcreteEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.MaterialCompanyEntity;
import com.sgb.kjwl.model.entity.MaterialDetailEntity;
import com.sgb.kjwl.model.entity.ParamsEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.manage.ShopInfoForCompanyTradesActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.view.ui.adapter.material.GoodsParamsAdapter;
import com.sgb.kjwl.view.ui.adapter.shopping.ShopBannerAdapter;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.widget.GoodsSpecificationsPopWindow;
import com.sgb.kjwl.viewmodel.shopping.ShopGoodsModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.DialogUtil;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.viewpager.CarouselViewPager;

import org.greenrobot.eventbus.EventBus;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

public class ShopGoodsInfoActivity extends AppActivity {
    private ActivityShopGoodsDetailBinding binding;
    @Inject
    ShopGoodsModel viewModel;
    /**
     * 是否是ScrollView主动动作
     * false:是ScrollView主动动作
     * true:是TabLayout 主动动作
     */
    private String id;
    private String from;
    private String companyId;
    private ShopBannerAdapter bannerAdapter;
    private GoodsSpecificationsPopWindow popWindow;
    private CarouselViewPager bannerViewpager;
    private ImageView[] tips;
    private ImageView[] memuTip;
    private int bannerCount;
    private ConcreteEntity concreteEntity;

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerMaterialComponent.builder().appComponent(appComponent).materialModule(new MaterialModule(this)).build().inject(this);
    }

    public static void start(Context context, String id, String from) {
        Intent intent = new Intent();
        intent.putExtra("id", id);
        intent.putExtra("from", from);
        intent.setClass(context, ShopGoodsInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {

        binding = DataBindingUtil.setContentView(this, R.layout.activity_shop_goods_detail);
        binding.include.ivBack.setVisibility(View.VISIBLE);
        binding.include.ivBack.setOnClickListener(this);
        binding.tvShop.setOnClickListener(this);
        binding.tvCall.setOnClickListener(this);
        binding.ivAdd.setOnClickListener(this);
        binding.ivMinus.setOnClickListener(this);
        binding.tvAddShoppingCar.setOnClickListener(this);
        binding.tvShoppingCar.setOnClickListener(this);
//        binding.tvSpecifications.setOnClickListener(this);
        binding.tvMessage.setOnClickListener(this);
        binding.include.titleView.setText("商品详情");
        popWindow = new GoodsSpecificationsPopWindow(ShopGoodsInfoActivity.this);
        popWindow.setBgView(binding.grayLayout);
        popWindow.setOnResultClick((key1, key2, key3) -> {

        });
    }


    @Override
    protected void init() {
        id = getIntent().getStringExtra("id");
        from = getIntent().getStringExtra("from");
        viewModel.getDetailModel(id);
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
            viewModel.getAuthInfo();
        }
        if ("SHOPPING_CAR".equals(from)) {
            binding.llBottom.setVisibility(View.GONE);
        } else {
            binding.llBottom.setVisibility(View.VISIBLE);
        }
    }

    public void refreshCarCount(Integer count) {
        if (count > 0) {
            binding.tvCarCount.setVisibility(View.VISIBLE);
            binding.tvCarCount.setText(count);
        } else {
            binding.tvCarCount.setVisibility(View.GONE);
        }

    }

    public void showProductInfo(MaterialDetailEntity data) {
        companyId = data.getShopId();
        viewModel.getCompanyModel(data.getShopId());
        initBanner(data.getImages());
        binding.tvTitle.setText(data.getCartTitle());
        binding.tvPriceTwo.setText("￥" + /*StringUtil.showPrice(*/data.getPrice()/*)*/ + "/" + data.getUnit());
        binding.tvDate.setText(data.getUpdateTime());
        binding.tvTaxRate.setText(data.getTax());
        if (data.getItemDesc() == null)
            return;
        Document doc = Jsoup.parseBodyFragment(data.getItemDesc());
        Elements elements = doc.select("img");
        for (Element each : elements) {
            each.attr("style", "width:100%");
        }
//        popWindow.setData(data.getCartTitle(), data.getImages().get(0));
        binding.webView.loadData(doc.html(), "text/html; charset=UTF-8", null);
        binding.webView.getSettings().setJavaScriptEnabled(true);
        binding.webView.getSettings().setSupportZoom(false);
        binding.webView.getSettings().setBuiltInZoomControls(false);
        binding.webView.getSettings().setUseWideViewPort(true);
        binding.webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        binding.webView.getSettings().setLoadWithOverviewMode(true);

//        Gson gson = new Gson();
//        JsonParser jsonParser = new JsonParser();
//        JsonArray jsonElements = jsonParser.parse(data.getParams()).getAsJsonArray();
//        ArrayList<ShopGoodsInfoActivity.MarkData> marks = new ArrayList<>();
//        for (JsonElement bean : jsonElements) {
//            ShopGoodsInfoActivity.MarkData markData = gson.fromJson(bean, ShopGoodsInfoActivity.MarkData.class);
//            marks.add(markData);
//        }
//
//        if (marks.size() > 0) {
//            binding.tv9.setText(marks.get(0).getK());
//            binding.tvMark.setText(marks.get(0).getV());
//        }

        ArrayList<ParamsEntity> list = new ArrayList<>();

        ParamsEntity params1 = new ParamsEntity();
        params1.setKey("品牌");
        params1.setValue(data.getBrandName());

        ParamsEntity params2 = new ParamsEntity();
        params2.setKey("计量单位");
        params2.setValue(data.getUnit());

        ParamsEntity params3 = new ParamsEntity();
        params3.setKey("仓储");
        params3.setValue(data.getStorageName());

        list.add(params1);
        list.add(params2);
        list.add(params3);

        for (ParamsEntity entity : data.getParams()) {
            ParamsEntity param = new ParamsEntity();
            param.setKey(entity.getKey());
            param.setValue(entity.getValue());
            list.add(param);
        }

        GoodsParamsAdapter goodsParamsAdapter = new GoodsParamsAdapter(this, list);
        binding.paramsList.setLayoutManager(new LinearLayoutManager(this));
        binding.paramsList.setAdapter(goodsParamsAdapter);

        viewModel.getShopImInfo(data.getShopId());
    }

    public void showCompanyInfo(MaterialCompanyEntity data) {
        binding.tvComSettledInTime.setText(data.getEstablishmentDate());
        binding.tvComName.setText(data.getCompanyName());
        binding.tvComBusiness.setText(data.getBusiness());
        binding.tvComAddress.setText(data.getCompanyAddress());
        binding.tvComReg.setText(data.getRegisteredCapital());
        binding.tvComInfo.setText(Html.fromHtml(data.getIntroduction()));
        binding.tvSgbTel.setText(data.getPhone());
        if (data.getIntroduction().equals("")) {
            binding.tvEnterpriseDesc.setVisibility(View.GONE);
        } else {
            binding.tvEnterpriseDesc.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_shop:
                ShopInfoForCompanyTradesActivity.startAct(getActivity(), companyId, "", 0, 0);
                break;
            case R.id.tv_call:
                DialogUtil.showTelDialog(this, "客服电话", "4000010051");
                break;
            case R.id.iv_add:
                int i = Integer.parseInt(binding.etNum.getText().toString());
                binding.etNum.setText(String.valueOf(i + 1));
                break;
            case R.id.iv_minus:
                int num = Integer.parseInt(binding.etNum.getText().toString());
                binding.etNum.setText(String.valueOf(num > 1 ? num - 1 : 1));
                break;
            case R.id.tv_add_shopping_car:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //LoginActivity.start(this);
                    jumpLogin();
                } else {
                    viewModel.checkToken("add_shopping_car");
                }
                break;
            case R.id.tv_shopping_car:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    //LoginActivity.start(this);
                    jumpLogin();
                } else {
                    viewModel.checkToken("shopping_car");
                }
                break;
//            case R.id.tv_specifications:
//                if (concreteEntity != null) {
//                    showPop();
//                } else {
//                    viewModel.getConcreteAttribute("20190901044506281");
//                }
//                MailListActivity.start(this);
//                break;
            case R.id.tv_message:
                if ("".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_TOKEN, ""))) {
                    jumpLogin();
                } else {
                    IMUtils.getInstance().buildSingleTalking(viewModel.shopImAccount.get());
//                    NimUIKit.startP2PSession(ShopGoodsInfoActivity.this, viewModel.shopImAccount.get());
                }
                break;
        }
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(ShopGoodsInfoActivity.this).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(this, EventConstant.EVENT_SHOP_GOODS_INFO_ACTIVITY_JUMP);
        }
    }

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(this));
        //开始拉取授权页
        DialogHelper.showProgressDialog(this, null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(ShopGoodsInfoActivity.this, EventConstant.EVENT_SHOP_GOODS_INFO_ACTIVITY_JUMP);
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    public void getConcreteSucc(ConcreteEntity concreteEntity) {
        this.concreteEntity = concreteEntity;
        popWindow.setData(concreteEntity);
        showPop();
    }

    private void showPop() {
        popWindow.showDownPopwindow(binding.grayLayout, true);

    }

    private class MarkData {
        private String k;
        private String v;

        public String getK() {
            return k;
        }

        public void setK(String k) {
            this.k = k;
        }

        public String getV() {
            return v;
        }

        public void setV(String v) {
            this.v = v;
        }
    }

    public void checkAddTokenView() {
        int itemNum = Integer.parseInt(binding.etNum.getText().toString());
        AddShoppingCar addShoppingCar = new AddShoppingCar();
        addShoppingCar.setAreacode(viewModel.getAreaCode());
        addShoppingCar.setItemId(id);
        addShoppingCar.setItemNum(String.valueOf(itemNum * 1000));
        viewModel.addShoppingCar(addShoppingCar);
    }

    public void checkTokenView() {
        Intent intent = new Intent();
        intent.putExtra("showPage", "FRAGMENT_SHOPPING");
        MainActivity.start(ShopGoodsInfoActivity.this, intent);
    }

    public void toLogin() {
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, "");
        MToast.showToast(this, "登录失效，请重新登录");
        //LoginActivity.start(this);
        jumpLogin();
    }

    //banner
    private void initBanner(List<String> bannerData) {
        if (bannerAdapter == null) {
            bannerAdapter = new ShopBannerAdapter(binding.bannerViewpager, null, this, BR.viewModel);
            binding.bannerViewpager.setAdapter(bannerAdapter);
            binding.bannerViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    setImageBackground(position % bannerCount);
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            binding.bannerViewpager.setLifeCycle(CarouselViewPager.RESUME);
            bannerCount = bannerData.size();
            initDots();
            bannerAdapter.setBannerEntityList(bannerData);
        }
    }

    private void initDots() {
        binding.dotLayout.removeAllViews();
        tips = new ImageView[bannerCount];
        for (int i = 0; i < bannerCount; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(R.drawable.select_shop_banner_dot);
            tips[i] = imageView;
            if (i == 0) {
                tips[i].setSelected(true);
            } else {
                tips[i].setSelected(false);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(new ViewGroup.LayoutParams(ResolutionUtil.dp2px(this, 1),
                    ResolutionUtil.dp2px(this, 12)));
            layoutParams.leftMargin = ResolutionUtil.dp2px(this, 4);
            layoutParams.rightMargin = ResolutionUtil.dp2px(this, 4);
            layoutParams.topMargin = ResolutionUtil.dp2px(this, 4);
            binding.dotLayout.addView(imageView, layoutParams);
        }
    }

    private void setImageBackground(int selectItems) {
        for (int i = 0; i < tips.length; i++) {
            if (i == selectItems) {
                tips[i].setSelected(true);
            } else {
                tips[i].setSelected(false);
            }
        }
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_SHOP_GOODS_INFO_ACTIVITY_JUMP);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }
}
